<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/5/16
 * Time: 13:43
 */
namespace App\Http\Controllers\FrontEnd;

use App\Events\RegSuccess;
use App\Http\Controllers\Controller;
use App\Models\MClassify;
use App\Models\MNews;
use App\Models\MProtocols;
use App\Models\MSmsCode;
use App\Models\MUser;
use App\Utils\GDUtil;
use App\Utils\TreeUtil;
use App\VModels\VVip;
use DB;
use Exception;
use Illuminate\Http\Request;
use Mail;


class FrontEndController extends Controller
{
    /**
     * @param Request $request 首页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function loginPage(Request $request)
    {
        $this->data['classify'] = MClassify::all();
        $this->data['assort'] = isset($request->id)?$request->id:3;
        $this->data['articles'] = MNews::where('cid',$request->id)->get();
        return view('front.login')->with($this->data);
    }

    /**
     * 内容页
     */
    public function viewPage(Request $request)
    {
        return view("front.view")->with($this->data);
    }

    /**
     * 转换路由
     */
    public function switchRoute(Request $request)
    {
        if ($request->id == 3) {
            return redirect()->route('login.page');
        } else {
            return redirect()->route('web.view');
        }
    }

    /**
     * 用户登录验证
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function loginAct(Request $request)
    {
        if (!$this->validateReq($request, MUser::loginRulesWithMsg(0), MUser::loginRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        //验证码检查
        if (!GDUtil::checkCode(GDUtil::YZM_USER_CODE, $request->yzm)) {
            $this->refreshYZM();
            $this->data = $this->makeJsCode(1, "验证码效验失败！");
            return response()->json($this->data);
        }

        //账号密码检查
        $user = MUser::where("username", strtolower($request->username))
            ->where("userpass", $request->userpass)->first();
        if (empty($user)) {
            $this->refreshYZM();
            $this->data = $this->makeJsCode(1, "账号密码验证失败！");
            return response()->json($this->data);
        }

        if ($user->ok_status === 0) {//未激活
            $this->refreshYZM();
            $this->data = $this->makeJsCode(1, "未激活用户不能登录！");
            return response()->json($this->data);
        }

        if ($user->status == MUser::$STATUS_STOP || $user->status == MUser::$STATUS_STOP_FREEZE) {
            $user->loginStatus($bool = false);
            $this->data = $this->makeJsCode(1, "该账户违规操作，已禁用！");
            return response()->json($this->data);
        }

        $user->loginStatus()->loginLog();
        $this->data = $this->makeJsCode(0, "登录成功！");
        return response()->json($this->data);
    }

    /**
     * 密码找回页
     * @return $this
     */
    public function findPassPage()
    {
        return view('front.find_pass')->with($this->data);
    }

    /**
     * 发送密码找回手机验证码
     * @param $tel  手机号
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendCode($name, $tel)
    {
        if (empty($tel) || empty($name)) {
            $this->data = $this->makeJsCode(1, "用户名或手机号不能为空！");
            return response()->json($this->data);
        }

        preg_match('/^1(3|4|5|7|8)\d{9}$/', $tel, $match);
        if (!$match) {
            $this->data = $this->makeJsCode(1, "请输入正确的手机号格式！");
            return response()->json($this->data);
        }

        //判断用户名和手机号正确性
        $user = MUser::where('username', $name)->first();
        if (empty($user)) {
            $this->data = $this->makeJsCode(1, "用户 $name 不存在！");
            return response()->json($this->data);
        }
        if ($user->mobile != $tel) {
            $this->data = $this->makeJsCode(1, "该手机号不是绑定手机号！");
            return response()->json($this->data);
        }

        $result = MSmsCode::send_yzm(8, $tel);
        if (is_bool($result)) {
            if ($result) {
                $this->data = $this->makeJsCode(0, "验证码发送成功，请注意查收！");
            } else {
                $this->data = $this->makeJsCode(1, "验证码发送失败，请重试！");
            }
        } else {
            $this->data = $this->makeJsCode(1, "您的操作过于频繁，请在 $result 秒后重新获取验证码！");
        }
        return response()->json($this->data);
    }

    /**
     * 找回密码操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function findPassAct(Request $request)
    {
        if ($request->flag == 1) {   //手机号找回
            if (!$request->has(['name', 'tel', 'code', 'sms_code', 'pass', 'repass'])) {
                $this->data = $this->makeJsCode(1, "请完善您的表单数据！");
                return response()->json($this->data);
            }
            //验证手机号格式
            preg_match('/^1(3|4|5|7|8)\d{9}$/', $request->tel, $match);
            if (!$match) {
                $this->data = $this->makeJsCode(1, "请输入正确的手机号格式！");
                return response()->json($this->data);
            }

            //判断用户名和手机号正确性
            $user = MUser::where('username', $request->name)->first();
            if (empty($user)) {
                $this->data = $this->makeJsCode(1, "用户 $request->name 不存在！");
                return response()->json($this->data);
            }
            if (empty($user->mobile)) {
                $this->data = $this->makeJsCode(1, "用户 $request->name 未绑定手机，无法找回！");
                return response()->json($this->data);
            }
            if ($user->mobile != $request->tel) {
                $this->data = $this->makeJsCode(1, "该手机号不是绑定手机号！");
                return response()->json($this->data);
            }

            //检查图片验证码
            if (!GDUtil::checkCode(GDUtil::YZM_USER_CODE, $request->code)) {
                $this->refreshYZM();
                $this->data = $this->makeJsCode(1, "验证码效验失败！");
                return response()->json($this->data);
            }

            //检查两次密码是否一致
            if ($request->pass !== $request->repass) {
                $this->data = $this->makeJsCode(1, "两次密码输入不一致！");
                return response()->json($this->data);
            }

            //检查短信验证码
            $sms_code = MSmsCode::check_code($request->tel, $request->sms_code, MSmsCode::$TYPE_TEL);
            if (is_bool($sms_code)) {
                if (!$sms_code) {
                    $this->data = $this->makeJsCode(1, "短信验证码输入错误！");
                    return response()->json($this->data);
                }
            } else {
                $this->data = $this->makeJsCode(1, "短信验证码已失效，请重新获取！");
                return response()->json($this->data);
            }

            //修改密码
            if ($request->type == 1) {  //找回登录密码
                $user->userpass = $request->pass;
            } elseif ($request->type == 2) {    //找回交易密码
                $user->safepass = $request->pass;
            }
            $user->save();

        } elseif ($request->flag == 2) {    //邮箱找回

            if (!$request->has(['e_name', 'email', 'e_code', 'email_code', 'e_pass', 'e_repass'])) {
                $this->data = $this->makeJsCode(1, "请完善您的表单数据！");
                return response()->json($this->data);
            }
            //验证邮箱格式
            preg_match('/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/', $request->email, $match);
            if (!$match) {
                $this->data = $this->makeJsCode(1, "请输入正确的邮箱格式！");
                return response()->json($this->data);
            }

            //判断用户名和邮箱正确性
            $user = MUser::where('username', $request->e_name)->first();
            if (empty($user)) {
                $this->data = $this->makeJsCode(1, "用户 $request->e_name 不存在！");
                return response()->json($this->data);
            }
            if (empty($user->email)) {
                $this->data = $this->makeJsCode(1, "用户 $request->e_name 未绑定邮箱，无法找回！");
                return response()->json($this->data);
            }
            if ($user->email != $request->email) {
                $this->data = $this->makeJsCode(1, "该邮箱不是绑定邮箱！");
                return response()->json($this->data);
            }

            //检查图片验证码
            if (!GDUtil::checkCode(GDUtil::YZM_USER_CODE, $request->e_code)) {
                $this->refreshYZM();
                $this->data = $this->makeJsCode(1, "验证码效验失败！");
                return response()->json($this->data);
            }

            //检查两次密码是否一致
            if ($request->e_pass !== $request->e_repass) {
                $this->data = $this->makeJsCode(1, "两次密码输入不一致！");
                return response()->json($this->data);
            }

            //检查邮箱验证码
            $email_code = MSmsCode::check_code($request->email, $request->email_code, MSmsCode::$TYPE_EMAIL);
            if (is_bool($email_code)) {
                if (!$email_code) {
                    $this->data = $this->makeJsCode(1, "邮箱验证码输入错误！");
                    return response()->json($this->data);
                }
            } else {
                $this->data = $this->makeJsCode(1, "邮箱验证码已失效，请重新获取！");
                return response()->json($this->data);
            }

            //修改密码
            if ($request->e_type == 1) {  //找回登录密码
                $user->userpass = $request->e_pass;
            } elseif ($request->e_type == 2) {    //找回交易密码
                $user->safepass = $request->e_pass;
            }
            $user->save();
        }

        if ($user->save()) {
            $this->data = $this->makeJsCode(0, "密码找回成功！");
        } else {
            $this->data = $this->makeJsCode(1, "密码找回失败！");
        }
        return response()->json($this->data);

//        if (!$request->has('tel')) {
//            $this->data = $this->makeJsCode(1, "请输入您要查找的用户名！");
//            return response()->json($this->data);
//        }
//
//        $user = MUser::where('username', $request->username)->first();
//        if (empty($user) || empty($user->email)) {
//            $this->data = $this->makeJsCode(1, "账户未绑定邮箱，无法找回！");
//            return response()->json($this->data);
//        }
//
//        try {
//            Mail::send('system.coms.findpass-template', ['user' => $user], function ($m) use ($user) {
//                $m->subject("密码找回邮件，请查收！")
//                    ->from(ini('MAIL_USERNAME'), cv('website.site_name'))
//                    ->to($user->email);
//            });
//            $this->data = $this->makeJsCode(0, "密码已发送至您的绑定邮箱！");
//        } catch (Exception $e) {
//            $this->data = $this->makeJsCode(1, "邮件发送失败，请重新尝试！");
//        }

//        return response()->json($this->data);
    }

    /**
     * 会员注册页面
     * @param string $no
     * @return $this
     */
    public function registerPage($no = "")
    {
        $this->data['puser'] = MUser::where('no', $no)->first();
        $this->data['protocol'] = MProtocols::first();
        //会员等级
        $vips = VVip::getVipList();
        $this->data['vips'] = empty($vips) ? [] : $vips;
        return view('front.register')->with($this->data);
    }

    /**
     * 注册新的会员
     */
    public function registerAct(Request $request)
    {
        if (cv("switch.reg_user") == 0) {
            $this->data = $this->makeJsCode(1, "该功能暂时关闭！");
            return response()->json($this->data);
        }

        if (!$this->validateReq($request, MUser::regRulesWithMsg(0), MUser::regRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }
        $user = new MUser();

        //检查会员是否重名
        if ($user->existUserName($request->name)) {
            $this->data = $this->makeJsCode(1, "用户名已经存在！");
            return response()->json($this->data);
        }

        //检查推荐人
        $puser = TreeUtil::checkPUserByName($request->pname);
        if (empty($puser)) {
            $this->data = $this->makeJsCode(1, "无效的推荐人！");
            return response()->json($this->data);
        }

        //检查该推荐人是否为报单中心
        if ($puser->bdzx_status !== 1) {
            $this->data = $this->makeJsCode(1, "推荐人不是报单中心！");
            return response()->json($this->data);
        }

        //检查节点人
        $nuser = TreeUtil::checkNUserByName($request->nname);
        if (empty($nuser)) {
            $this->data = $this->makeJsCode(1, "无效的节点人！");
            return response()->json($this->data);
        }

        //检查节点人位置是否已满
        $addr = TreeUtil::getNodeAddrByUser($nuser);
        if ($addr == 0) {
            $this->data = $this->makeJsCode(1, "节点人位置已满！");
            return response()->json($this->data);
        }

        //检查登录密码和确认密码是否一致
        if ($request->pass !== $request->repass) {
            $this->data = $this->makeJsCode(1, "两次登录密码输入不一致！");
            return response()->json($this->data);
        }

        //检查交易密码和确认密码是否一致
        if ($request->safepass !== $request->resafepass) {
            $this->data = $this->makeJsCode(1, "两次交易密码输入不一致！");
            return response()->json($this->data);
        }

        //检查邮箱是否已被注册
        $email = MUser::where('email', $request->email)->first();
        if (!empty($email)) {
            $this->data = $this->makeJsCode(1, "该邮箱已被注册！");
            return response()->json($this->data);
        }

        //检查手机号是否已被注册
        $tel = MUser::where('mobile', $request->tel)->first();
        if (!empty($tel)) {
            $this->data = $this->makeJsCode(1, "该手机号已被注册！");
            return response()->json($this->data);
        }

        //检查短信验证码
        $sms_code = MSmsCode::check_code($request->tel, $request->sms_code, MSmsCode::$TYPE_TEL);
        if (is_bool($sms_code)) {
            if (!$sms_code) {
                $this->data = $this->makeJsCode(1, "短信验证码输入错误！");
                return response()->json($this->data);
            }
        } else {
            $this->data = $this->makeJsCode(1, "短信验证码已失效，请重新获取！");
            return response()->json($this->data);
        }

        try {
            DB::transaction(function () use ($request, $puser, $nuser, &$user) {
                if ($user->regUser($request, $puser, $nuser)) {

                    event(new RegSuccess($user));   //发送注册成功事件通知
                    $this->data = $this->makeJsCode(0, "注册成功！");

                } else {

                    DB::rollBack();
                    $this->data = $this->makeJsCode(1, "注册失败！");

                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "注册失败！");
        }
        return response()->json($this->data);
    }
}